<template>
	<view class="uni-search-list">
		<!-- 搜索框 -->
		<view class="search-header uni-header uni-header-sticky box box-center bcl-main p-10" style="padding-right: 0;">
			<view class="search-box box-1">
				<uni-search-box v-model="keyword" @search="search"></uni-search-box>
			</view>

			<!-- 类型切换 -->
			<view class="toggle-btn pointer pointer-filter ml-10" :class="{ active: type == 1 }" @tap="toggleType(1)">任务</view>
			<view class="toggle-btn pointer pointer-filter mr-10" :class="{ active: type == 3 }" @tap="toggleType(3)">人才</view>
		</view>

		<!-- 筛选列表 -->
		<view class="filter-header uni-header uni-header-sticky box bcl-white border border-bottom">
			<view class="sort-list box box-1">
				<view class="item pointer" @click="getLocationInfo">
					{{ city }}
					</button>
				</view>
				<view class="item pointer" :class="{ 'cl-main': index == currentSortIndex }" v-for="(item, index) in sorts" :key="index"
				 @tap="onSortChange(index)">{{ item.label }}</view>
			</view>

			<!-- 筛选按钮 -->
			<view class="filter-btn pointer box box-column-center">
				<navigator :url="filterPageUrl">
					<image src="../static/images/menu.png" style="width: 50rpx;height: 50rpx;"></image>
				</navigator>
			</view>
		</view>

		<!-- 数据列表 -->
		<view class="data-list container uni-animation-fade" v-if="list.length">
			<view class="item mb-10" v-for="(item, index) in list" :key="index">
				<uni-task-item :item="item" v-if="type == 1"></uni-task-item>
				<uni-service-item :item="item" v-else-if="type == 2"></uni-service-item>
				<uni-servicer-item :item="item" v-else></uni-servicer-item>
			</view>
		</view>

		<!-- 加载更多组件 -->
		<uni-load-more :status="loadMoreStatus" @retry="listData"></uni-load-more>
	</view>
</template>

<script>
	// import { mapState } from "vuex";

	import {
		mapState,
		mapActions
	} from "vuex";

	import uniSearchBox from "@/components/searchBox";
	import uniTaskItem from "@/components/taskItem";
	import uniServiceItem from "@/components/serviceItem";
	import uniServicerItem from "@/components/servicerItem";
	import uniLoadMore from "@/components/loadMore";

	import {
		listTask
	} from "@/apis/task";
	import {
		userInfo
	} from "@/apis/user";
	import {
		listService,
		listServicer
	} from "@/apis/service";


	import {
		getLocationInfo
	} from "@/utils/common";

	export default {
		name: "uniSearchList",

		props: {
			// 分类ID
			cId: {
				type: String,
				default: "",
			},
		},

		data() {
			return {
				taskForm: {
					city: "全国"
				},

				locationInfo: {}, // 定位信息

				protocol: true, // 是否同意协议
				useLocation: true, // 是否有授权定位
				type: 1, // 页面类型，1任务、2服务、3服务商
				keyword: "", // 搜索关键词
				list: [], // 数据列表

				// 任务排序
				taskSorts: [{
						label: "推荐",
						value: 0,
					},
					{
						label: "关注",
						value: 1,
					},

				],
				// 服务排序
				serviceSorts: [{
						label: "综合",
						value: "",
					},
					{
						label: "金额",
						value: "cash",
					},
					{
						label: "成交量",
						value: "sales_num",
					},
					{
						label: "好评数",
						value: "good_comment",
					},
				],
				// 服务商排序
				servicerSorts: [{
						label: "推荐",
						value: 2,
					},
					{
						label: "关注",
						value: 1,
					},
				],

				currentSortIndex: 0,

				// 任务筛选结果
				taskFilter: {
					type: "",
					status: "",
					province: "",
				},

				// 服务筛选结果
				serviceFilter: {
					category: "",
					type: "",
				},

				// 服务商筛选结果
				servicerFilter: {
					category: "",
					province: "",
				},

				page: 1,
				loadMoreStatus: 1,
			};
		},
		created() {
			let url = this.userInfo;
			if (url) {
				this.userInfoas();
			}

			setTimeout(() => {
				uni.$on("searchListRefresh", () => {
					this.listData(true, true);
				});
				this.listData();

				// 任务筛选
				if (this.type == 1) {
					uni.$on("reachBottom", this.listData);

					uni.removeStorageSync("currentTaskFilter");
					uni.$on("reload", () => {
						this.taskFilter =
							uni.getStorageSync("currentTaskFilter") || this.taskFilter;
						this.listData(true);
					});

					// 搜索页面跳转过来
					uni.$on("search", () => {
						this.keyword = uni.getStorageSync("currentKeyWord") || "";
						this.listData(true);
					});
				} else if (this.type == 2) {
					uni.$on("reachBottom", this.listData);

					// 服务筛选
					uni.removeStorageSync("currentServiceFilter");
					uni.$on("reload", () => {
						this.serviceFilter =
							uni.getStorageSync("currentServiceFilter") || this.serviceFilter;
						this.listData(true);
					});
				} else if (this.type == 3) {
					uni.$on("reachBottom", this.listData);

					// 服务筛选
					uni.removeStorageSync("currentServicerFilter");
					uni.$on("reload", () => {
						this.servicerFilter =
							uni.getStorageSync("currentServicerFilter") || this.servicerFilter;
						this.listData(true);
					});
				}
			}, 500);
		},
		onShow() {},
		methods: {
			getLocationInfo() {
				uni.navigateTo({
					url: "/pages/index/city"
				});
			},
			/**
			 * 切换类型
			 */
			toggleType(type) {
				this.type = type;
				this.keyword = "";
				this.listData(true);
			},

			async userInfoas() {
				let {
					data
				} = await userInfo();
				var a = 4,
					arr = '';
				for (let i = 0; i < 2; i++) {
					a++;
					// console.log(data.tags[i])
					arr = {
						// label: data.tags[i].substring(0,2),
						label: data.tags[i],
						value: 3,
						extend: data.tags[i],
					}
					this.taskSorts.push(arr);
					this.servicerSorts.push(arr);
				}

				// console.log("arr",arr);

				// console.log("taskSorts",this.taskSorts);
			},


			/*
			 * 数据列表
			 */
			async listData(refresh = false, successToast = false) {
				var longitude = "";
				var latitude = "";
				// uni.getLocation({
				// 	type: 'wgs84',
				// 	geocode: true, //设置该参数为true可直接获取经纬度及城市信息
				// 	success: function(res) {
				// 		longitude = res.longitude
				// 		latitude = res.latitude
				// 	},
				// 	fail: function() {
				// 		uni.showToast({
				// 			title: '获取地址失败，将导致部分功能不可用',
				// 			icon: 'none'
				// 		});
				// 	}
				// });
				try {
					// 刷新重置
					if (refresh) {
						this.page = 1;
						this.list = [];
					}

					// 参数
					let params = {};
					// 任务列表
					if (this.type == 1) {
						params = {
							cate_id: this.cId,
							page: this.page,
							taskName: this.keyword,
							desc: this.sorts[this.currentSortIndex].value,
							extend: this.sorts[this.currentSortIndex].label,
							type: this.taskFilter.type,
							status: this.taskFilter.status,
							province: this.taskForm.city //this.taskFilter.province,
						};
					} else if (this.type == 2) {
						// 服务列表
						params = {
							page: this.page,
							title: this.keyword,
							desc: this.sorts[this.currentSortIndex].value,
							extend: this.sorts[this.currentSortIndex].label,
							type: this.serviceFilter.type,
							category: this.serviceFilter.category,
						};

					} else {
						// 服务商列表						
						params = {
							page: this.page,
							keywords: this.keyword || '',
							category: this.servicerFilter.category || '',
							province: this.taskForm.city, //this.servicerFilter.province || '',
							lat: latitude,
							lng: longitude
						};

						let employee_praise_rate = this.sorts[this.currentSortIndex].value;
						if (employee_praise_rate !== "")
							params.employee_praise_rate = employee_praise_rate;

					}
					console.log("--->请求参数：",params);
					this.loadMoreStatus = 0; // 开始请求					
					let {
						code,
						data
					} =
					this.type == 1 ?
						await listTask(params) :
						this.type == 2 ?
						await listService(params) :
						await listServicer(params);
					if (code == 200) {
						if (successToast) this.$toast("刷新成功");
						uni.stopPullDownRefresh();

						// 刷新重置
						if (refresh) {
							this.page = 1;
							this.list = [];
						}
						if (this.page === 1 && data.data.length === 0 && this.keyword.length == 0) {

							this.list = this.list.concat(data.recommend || []);
							this.loadMoreStatus = 1; // 请求成功
							this.loadMoreStatus = 3; // 没有更多了
							
						} else {
							this.list = this.list.concat(data.data || []);
							this.loadMoreStatus = 1; // 请求成功
							if (data.data.length == 0) this.loadMoreStatus = 3; // 没有更多了
							if (data.total == 0) this.loadMoreStatus = 5; // 毛都没
							this.page += 1;

						}

						// if (this.type == 1) {
						// 	this.list = this.list.concat(data.recommend || []);
						// } else {
						// 	this.list = this.list.concat(data.data || []);
						// }


					} else {
						this.loadMoreStatus = 2; // 请求失败
					}
				} catch (err) {
					this.loadMoreStatus = 2; // 请求失败
				}
			},

			/*
			 * 搜索
			 */
			async search() {
				uni.hideKeyboard();
				this.listData(true);
			},

			/*
			 * 排序更换
			 */
			onSortChange(index) {
				console.log(index);
				if(index === 1 && !this.$store.state.userInfo){
					uni.navigateTo({
						url:'/user/login'
					});
					return;
				}
				this.currentSortIndex = index;
				this.listData(true);
			},
		},

		watch: {
			city: function(o, n) {
				this.listData(true);
			}
		},

		computed: {
			city() {
				this.taskForm.city = this.$store.state.city;
				return this.$store.state.city.length === 0 ? '定位' : this.$store.state.city;
			},
			// 当前排序列表
			sorts() {
				return this.type == 1 ?
					this.taskSorts :
					this.type == 2 ?
					this.serviceSorts :
					this.servicerSorts;
			},

			filterPageUrl() {
				return this.type == 1 ?
					"/filter/task" :
					this.type == 2 ?
					"/filter/service" :
					"/filter/servicer";
			},

			...mapState(["currentFilters", "userInfo"]),

			// ...mapState(["classifys", "currentClassifys","userInfo", "currentServices"]),
		},

		components: {
			uniSearchBox,
			uniTaskItem,
			uniServiceItem,
			uniServicerItem,
			uniLoadMore,
		},
	};
</script>

<style lang="scss" scoped>
	.uni-search-list {
		.search-header {
			top: -110upx;

			.toggle-btn {
				width: 100upx;
				height: 70upx;
				line-height: 70upx;
				text-align: center;
				color: white;
				border-radius: 100px;

				&:active {
					background-color: transparent;
				}

				&.active {
					background-color: white;
					color: $color-main;
				}
			}
		}

		// 筛选
		.sort-list {
			position: relative;
			overflow-x: auto;
			white-space: nowrap;

			.item {
				padding: 25upx 20upx;
			}
		}

		.filter-btn {
			padding: 20upx;
			line-height: 1;
		}
	}
</style>
